/*
 * Project:		ListenMyStory
 * Purpose:
 * 				[+] Android Publish Book (Image + Text)
 * 				 - Autobiography(UCC, Let me tell you a little something about me)
 * 				 - Novel (General, Game Novel, ...)
 * 				 - Gallery (Pictures + Descriptions)
 * Author:		Ho-Jung Kim (godmode2k@hotmail.com)
 * Date:		Since September 15, 2010
 * Latest modified:	April 19, 2011
 * Filename:	ListenMyStoryApp.java
 * 
 * Source:
 * Note:
 * ----------------------------------------
 * TODO:
 *
 * URGENT!!!
 * TODO:
 * 
 * License:
	This file is part of ListenMyStory.
	ListenMyStory is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	ListenMyStory is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with ListenMyStory.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.JustListen.ListenMyStory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.Application;
import android.content.res.AssetFileDescriptor;
import android.os.Environment;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;



public class ListenMyStoryApp extends Application {
	private static final String TAG = "ListenMyStoryApp";
	private static final boolean m_isDebugOn = true;
	
	// -----------------------------
	// Resource
	// -----------------------------
	private xmlResManage m_xmlResManage = new xmlResManage();
	private List<xmlResManage> m_xmlResList = new ArrayList<xmlResManage>();
	private static final String m_strConfXmlFile = "conf.xml";
	private static final String m_strTAG_FontSize = "fontsize=";
	private static final String m_strTAG_ResPath = "respath=";
	private static final String m_strTAG_LastFile = "lastfile=";
	
	public class CConfManager {
		private int m_FontSize = 14;
		// Prefixed mounted external storage directory such as "/sdcard/" or "/mnt/sdcard/"
		// It will be creates like: "/sdcard/xxx" or "/mnt/sdcard/xxx"
		private String m_strResPath = "ListenMyStory";
		private String m_strLastFile = "";

		public CConfManager() {}
		public void SetFontSize(int fontSize) { m_FontSize = fontSize; }
		public void SetResLocation(String strResPath) { m_strResPath = strResPath; }
		public void SetLastFile(String strLastFile) { m_strLastFile = strLastFile; }
		public String GetFontSize() { return Integer.toString( m_FontSize ); }
		public String GetResPath() { return m_strResPath; }
		public String GetLastFile() { return m_strLastFile; }
	}
	private CConfManager m_ConfManager = new CConfManager();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate() {
        __DEBUG__( "onCreate()" );
    }

    @Override
    public void onTerminate() {
        __DEBUG__( "onTerminate()" );
    }
    
    public void __DEBUG__(String str) {
    	if( m_isDebugOn )
    		Log.d( TAG, str );
    }
    
    public void __DEBUG_ERROR__(String str) {
   		Log.d( TAG, str );
    }
    
    public void CLEAN_UP_ALL() {
    	__DEBUG__( "CLEAN_UP_ALL()" );
    	
    	if( m_xmlResManage != null )
    		m_xmlResManage = null;

    	if( m_xmlResList != null ) {
    		m_xmlResList.clear();
    		m_xmlResList = null;
    	}
    }
    
    public boolean SetXmlResManage(List<xmlResManage> xmlResList) {
    	boolean ret = true;
    	
    	__DEBUG__( "SetXmlResManage()" );

    	if( m_xmlResManage == null )
    		m_xmlResManage = new xmlResManage();

    	if( m_xmlResList == null )
    		m_xmlResList = new ArrayList<xmlResManage>();

    	if( xmlResList != null )
    		m_xmlResList = xmlResList;
    	else
    		ret = false;
    	
    	return ret;
    }

    public List<xmlResManage> GetXmlResManage() {
    	__DEBUG__( "GetXmlResManage()" );

    	if( m_xmlResList != null )
    		return m_xmlResList;
    	else
    		return null;
    }
    
    public CConfManager GetConfManager() {
    	__DEBUG__( "GetConfManager()" );
    	
    	// Load a preference.xml
    	// Setup the CConfManager

    	if( m_ConfManager != null )
    		return m_ConfManager;
    	else
    		return null;
    }
    
    public boolean SetCreatesResDirectory() {
    	__DEBUG__( "SetCreatesResDirectory()" );

    	boolean ret = true;
    	
		String strFilePath = "./";
		String strFilePathInt = "";
		//String strFilePathExt = "/sdcard/";
		String strFilePathExt = android.os.Environment.getExternalStorageDirectory().getPath();
		strFilePathExt = strFilePathExt + "/";
		//File path = Environment.getExternalStorageDirectory();

		__DEBUG__( "SetCreatesResDirectory(): External Storage = " + Environment.getExternalStorageState() );
		
		// Checks Mount
		if( !android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED) ) {
			Toast.makeText( this, getResources().getString(R.string.Export_ExternalStorageHasNotBeenMounted), Toast.LENGTH_SHORT ).show();
			return false;
		}

		if( m_ConfManager != null )
			strFilePath = strFilePathExt + m_ConfManager.GetResPath();
		else {
			__DEBUG_ERROR__( "SetCreatesResDirectory(): m_ConfManager == NULL" );
			return false;
		}

		__DEBUG__( "SetCreatesResDirectory(): External Storage Directory = " + strFilePath );
		
		if( !(new File(strFilePath).exists()) ) {
			// Create a directory
			if( (new File(strFilePath).mkdir()) ) {
				__DEBUG__( "SetCreatesResDirectory(): \"" + strFilePath + "\" created" );
				Toast.makeText( this, "\"" + strFilePath + "\" " + getResources().getString(R.string.Export_CreatedDirectory), Toast.LENGTH_SHORT ).show();
			}
			else {
				__DEBUG_ERROR__( "SetCreatesResDirectory(): Fail to a created directory \"" + strFilePath + "\"" );
				Toast.makeText( this, "\"" + strFilePath + "\" " + getResources().getString(R.string.Export_Error_CreatedDirectory), Toast.LENGTH_SHORT ).show();
				return false;
			}
		}

    	return ret;
    }

    public boolean SetSaveConf() {
    	__DEBUG__( "SetSaveConf()" );

    	boolean ret = true;

    	if( m_ConfManager != null ) {
    		String strConf = null;

/*
    		strConf = "<rss version=\"2.0\">";
			strConf += "    <contents>";
			strConf += "        <item>";
			strConf += "            <fontsize>";
			strConf += m_ConfManager.GetFontSize();
			strConf += "</fontsize>";
			strConf += "            <respath>";
			strConf += m_ConfManager.GetResLocation();
			strConf += "</respath>";
			strConf += "        </item>";
			strConf += "    </contents>";
			strConf += "</rss>";
*/

    		strConf = m_strTAG_FontSize;
			strConf += m_ConfManager.GetFontSize();
			strConf += "\n";
			strConf += m_strTAG_ResPath;
			strConf += m_ConfManager.GetResPath();
			strConf += "\n";
			strConf += m_strTAG_LastFile;
			strConf += m_ConfManager.GetLastFile();
			strConf += "\n";

			__DEBUG__( "SetSaveConf(): " + strConf );

    		// Save as a xml
    		try {
    			FileOutputStream f = openFileOutput( m_strConfXmlFile, MODE_WORLD_WRITEABLE );
    			f.write( strConf.getBytes() );
    			f.close();
    			//deleteFile( m_strConfXmlFile );
    		}
    		catch (IOException e) {
    			// TODO Auto-generated catch block
    			//e.printStackTrace();
    			__DEBUG_ERROR__( "SetSaveConf(): IOException: " + e.getMessage() );
    			return false;
    		}
    		catch( Exception e ) {
    			// TODO Auto-generated catch block
    			//e.printStackTrace();
    			__DEBUG_ERROR__( "SetSaveConf(): Exception: " + e.getMessage() );
    			return false;
    		}
    	}
    	
    	return ret;
    }
    
    public boolean GetLoadConf() {
    	__DEBUG__( "GetLoadConf()" );

    	boolean ret = true;

    	if( m_ConfManager == null ) {
    		__DEBUG_ERROR__( "GetLoadConf(): m_ConfManager == NULL" );
    		return false;
    	}

		try {
			int MAX_BUF_SIZE = 2048;
			FileInputStream f = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			String strGetLine;
			StringBuilder sb = new StringBuilder();

			String strFontSize = "";
			String strResPath = "";
			String strLastFile = "";

			f = openFileInput( m_strConfXmlFile );
			if( f.available() <= 0 ) {
				__DEBUG_ERROR__( "GetLoadConf(): \"" + m_strConfXmlFile + "\" not available" );
				f.close();
				return false;
			}

			isr = new InputStreamReader( f );
			br = new BufferedReader( isr );

			try {
				while( (strGetLine = br.readLine()) != null ){ 
					sb.append( strGetLine ); 
					sb.append( "\n" );
					
					__DEBUG__( "GetLoadConf(): GETLINE = " + strGetLine );

					if( strGetLine.contains(m_strTAG_FontSize) )
						strFontSize = strGetLine.replace( m_strTAG_FontSize, "" );
					else if( strGetLine.contains(m_strTAG_ResPath) )
						strResPath = strGetLine.replace( m_strTAG_ResPath, "" );
					else if( strGetLine.contains(m_strTAG_LastFile) )
						strLastFile = strGetLine.replace( m_strTAG_LastFile, "" );
				}
				br.close();
				isr.close();

				//strFontSize = strFontSize.replace( m_strTAG_FontSize, "" );
				//strResPath = strResPath.replace( m_strTAG_ResPath, "" );
				//strLastFile = strLastFile.replace( m_strTAG_LastFile, "" );
				
				__DEBUG__( "GetLoadConf(): " + "Font Size = " + strFontSize );
				__DEBUG__( "GetLoadConf(): " + "Resource Path = " + strResPath );
				__DEBUG__( "GetLoadConf(): " + "Last Opened File = " + strLastFile );
				
				m_ConfManager.SetFontSize( Integer.parseInt(strFontSize) );
				m_ConfManager.SetResLocation( strResPath );
				m_ConfManager.SetLastFile( strLastFile );
			}
			catch( IOException e ) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				__DEBUG_ERROR__( "GetLoadConf(): IOException: " + e.getMessage() );
				return false;
			}
			catch( Exception e ) {
    			// TODO Auto-generated catch block
    			//e.printStackTrace();
				__DEBUG_ERROR__( "GetLoadConf(): Exception: " + e.getMessage() );
    			return false;
    		}

			f.close();
		}
		catch( FileNotFoundException e ) {
			__DEBUG_ERROR__( "GetLoadConf(): FileNotFoundException: " + e.getMessage() );
			__DEBUG_ERROR__( "GetLoadConf(): FileNotFoundException: Create a default configuration" );
			SetSaveConf();
			return false;
		}
		catch( IOException e ) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			__DEBUG_ERROR__( "GetLoadConf(): IOException: " + e.getMessage() );
			return false;
		}
		catch( Exception e ) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			__DEBUG_ERROR__( "GetLoadConf(): Exception: " + e.getMessage() );
			return false;
		}
		
		return ret;
    }
}


/*
	public boolean SetSaveResourceToZip() {
    	__DEBUG__( "SetSaveResourceToZip()" );

    	boolean ret = true;

    	String strConfFile = null;
    	if( m_ConfManager != null ) {
    		int len = (m_ConfManager.GetResPath().length() - 1);
    		if( m_ConfManager.GetResPath().charAt(len) != '/' )
    			strConfFile = m_ConfManager.GetResPath() + "/" + m_strConfXmlFile;
    		else
    			strConfFile = m_ConfManager.GetResPath() + m_strConfXmlFile;
    	}
    	else {
    		__DEBUG_ERROR__( "GetLoadConf(): m_ConfManager == NULL" );
    		return false;
    	}

		try {
			int MAX_BUF_SIZE = 2048;
			FileInputStream f = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			String strGetLine;
			StringBuilder sb = new StringBuilder();

			String strFontSize = null;
			String strResPath = null;

			{
				try {
					// TODO: Internal/External Storage
					String strFilePath = "./";
					String strFilePathInt = "";
					//String strFilePathExt = "/sdcard/";
					String strFilePathExt = Environment.getExternalStorageDirectory().getPath();
					strFilePathExt = strFilePathExt + "/";

					byte[] buf_readBytes = new byte[1024];
					int readBytes = 0;
					int offset = 0;
					int count = 1024;
					
					__DEBUG__( "SetSaveResourceToZip(): External Storage = " + Environment.getExternalStorageState() );
					
					// Checks Mount
					if( android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED) ) {
						File path = Environment.getExternalStorageDirectory();
						StatFs stat = new StatFs( path.getPath() );
						long blockSize = stat.getBlockSize();
						long availableBlocks = stat.getAvailableBlocks();
						{
							// Compare with size of the resource
							//if( (availableBlocks * blockSize) < afd.getLength() ) {
							//	//Toast.makeText( this, "Out of External Storage Space", Toast.LENGTH_SHORT ).show();
							//	Toast.makeText( this, getResources().getString(R.string.Export_ExternalStorageFull), Toast.LENGTH_SHORT ).show();
							//	return false;
							//}
						}
					}
					else {
						//Toast.makeText( this, "External Storage Has Not Been Mounted, Mount First", Toast.LENGTH_SHORT ).show();
						Toast.makeText( this, getResources().getString(R.string.Export_ExternalStorageHasNotBeenMounted), Toast.LENGTH_SHORT ).show();
						return false;
					}

					strFilePath = strFilePathExt;
					__DEBUG__( "SetSaveResourceToZip(): External Storage Directory = " + strFilePath );
					//Toast.makeText( this, strFilePath, Toast.LENGTH_SHORT ).show();
					
					if( !(new File(strFilePath).exists()) ) {
						// Create a directory
						if( (new File(strFilePath).mkdir()) ) {
							__DEBUG__( "SetSaveResourceToZip(): \"" + strFilePath + "\" created" );
							Toast.makeText( this, strFilePath + getResources().getString(R.string.Export_CreatedDirectory), Toast.LENGTH_SHORT ).show();
						}
						else {
							__DEBUG_ERROR__( "SetSaveResourceToZip(): Fail to a created directory \"" + strFilePath + "\"" );
							Toast.makeText( this, strFilePath + getResources().getString(R.string.Export_Error_CreatedDirectory), Toast.LENGTH_SHORT ).show();
							return false;
						}
					}
				}
				catch( Exception e ) {
					__DEBUG_ERROR__( "SetSaveResourceToZip(): Exception: " + e.getMessage() );
					return false;
				}
			}
		}
		catch( Exception e ) {
			__DEBUG_ERROR__( "SetSaveResourceToZip(): Exception: " + e.getMessage() );
			return false;
		}
	}
*/


//-------------------------------------------
// __EOF__
//-------------------------------------------
